package com.leantech.android.browser.ui.browser.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import coil.load
import com.cscj.android.repository.db.entity.ShortCutEntryEntity
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.ItemShortCutEntryBinding
import com.leantech.android.browser.skin.SkinManager
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.show
import com.cscj.android.utils.BitmapUtils.asBitmap
import com.cscj.android.utils.UrlUtils
import com.qmuiteam.qmui.util.QMUIResHelper

class ShortCutEntryAdapter(private val adapterCallback: ShortCutEntryAdapterCallback) :
    ListAdapter<ShortCutEntryEntity, ShortCutEntryAdapter.ShortCutEntryViewHolder>(diffCallback) {

    companion object {
        const val maxColumnCount = 5
        const val maxRowCount = 3
        private const val itemTypeEntry = 1
        private const val itemTypeAdd = 2

        private const val PayloadEditMode = 1
        private const val PayloadDarkMode = 2

        private val diffCallback = object : DiffUtil.ItemCallback<ShortCutEntryEntity>() {
            override fun areItemsTheSame(
                oldItem: ShortCutEntryEntity, newItem: ShortCutEntryEntity
            ): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(
                oldItem: ShortCutEntryEntity, newItem: ShortCutEntryEntity
            ): Boolean {
                return oldItem == newItem
            }
        }
    }

    private var editMode: Boolean = false

    var dataCount = 0
        private set

    fun updateEditMode(on: Boolean) {
        if (on == editMode) return
        editMode = on
        notifyItemRangeChanged(0, dataCount, PayloadEditMode)
    }

    fun updateButtonSkin() {
        notifyItemChanged(itemCount - 1, PayloadDarkMode)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShortCutEntryViewHolder {
        val binding =
            ItemShortCutEntryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ShortCutEntryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ShortCutEntryViewHolder, position: Int) {
        when (getItemViewType(position)) {
            itemTypeEntry -> {
                holder.bind(getItem(position), editMode, adapterCallback)
            }

            itemTypeAdd -> {
                holder.bindForAdd(adapterCallback)
            }
        }
    }

    override fun onBindViewHolder(
        holder: ShortCutEntryViewHolder, position: Int, payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            payloads.forEach { payload ->
                when (payload) {
                    PayloadEditMode -> {
                        holder.bind(getItem(position), editMode, adapterCallback)
                    }

                    PayloadDarkMode -> {
                        holder.bindForAdd(adapterCallback)
                    }

                    else -> {
                        super.onBindViewHolder(holder, position, payloads)
                    }
                }

            }
        }

    }

    override fun submitList(list: List<ShortCutEntryEntity>?, commitCallback: Runnable?) {
        dataCount = list?.size ?: 0
        super.submitList(list, commitCallback)
    }

    override fun submitList(list: List<ShortCutEntryEntity>?) {
        dataCount = list?.size ?: 0
        super.submitList(list)
    }

    override fun getItemViewType(position: Int): Int {
        val rawItemCount = super.getItemCount()
        return if (position < rawItemCount) itemTypeEntry else itemTypeAdd
    }

    override fun getItemCount(): Int {
        val rawItemCount = super.getItemCount()
        return rawItemCount + 1
    }

    interface ShortCutEntryAdapterCallback {
        fun onEntryClicked(entry: ShortCutEntryEntity)

        fun onEntryAddClicked()

        fun onEntryLongClicked(entry: ShortCutEntryEntity)

        fun onEntryRemoveClicked(entry: ShortCutEntryEntity)
    }

    class ShortCutEntryViewHolder(private val binding: ItemShortCutEntryBinding) :
        ViewHolder(binding.root) {

        fun bind(
            data: ShortCutEntryEntity,
            editMode: Boolean,
            adapterCallback: ShortCutEntryAdapterCallback
        ) {
            binding.text.text = data.name
            when {
                data.isHistoryRoot() -> {
                    binding.image.load(R.drawable.icon_history_root)
                }

                data.isFavoriteRoot() -> {
                    binding.image.load(R.drawable.icon_favorites_root)
                }

                else -> {
                    val icon = data.icon
                    if (!icon.isNullOrBlank()) {
                        if (UrlUtils.isUrl(icon)) {
                            binding.image.load(icon)
                        } else {
                            binding.image.load(icon.asBitmap())
                        }
                    } else {
                        binding.image.load(R.drawable.icon_default_link)
                    }
                }
            }

            updateEditMode(data, editMode, adapterCallback)
        }

        fun updateEditMode(
            data: ShortCutEntryEntity,
            editMode: Boolean,
            adapterCallback: ShortCutEntryAdapterCallback
        ) {
            binding.btnRemove.show(editMode)

            if (editMode) {
                binding.root.setOnClickListener(null)
                binding.root.setOnLongClickListener(null)
                binding.btnRemove.onThrottleClick {
                    adapterCallback.onEntryRemoveClicked(data)
                }
            } else {
                binding.root.onThrottleClick {
                    adapterCallback.onEntryClicked(data)
                }

                binding.root.setOnLongClickListener {
                    adapterCallback.onEntryLongClicked(data)
                    true
                }
            }
        }

        fun bindForAdd(adapterCallback: ShortCutEntryAdapterCallback) {
            binding.image.load(
                QMUIResHelper.getAttrDrawable(
                    itemView.context,
                    SkinManager.currentTheme(itemView.context),
                    R.attr.app_skin_icon_entry_add
                )
            )
            binding.text.setText(R.string.text_add)
            binding.root.onThrottleClick {
                adapterCallback.onEntryAddClicked()
            }
        }

    }


}